use strict;

use vars qw($VERSION %IRSSI);
use Irssi::TextUI;

$VERSION = '0.1';
%IRSSI = (
   name        => 'peep',
   authors     => 'Charlie von Metzradt',
   contact     => 'http://sleepygeek.org',
   url         => 'http://sleepygeek.org',
   description => 'Client enhancement script for use with the peep twitter-irc gateway.',
   license     => 'GPL',
);

Irssi::print('peep integration:');
Irssi::print('   Enable statusbar item: /statusbar window add peep');


my ($input_length, $message_limit, $statusbar_registered);

$input_length = 0;
$message_limit = 140;
$statusbar_registered = 0;

sub peep_statusbar
{
   my ($item, $get_size_only) = @_;
   
   my $chars_remaining = $message_limit - $input_length;
   my $prefix = "";

   if($input_length > $message_limit) {
      $prefix = "%R"; # Red
   } elsif($input_length > $message_limit - 10) {
      $prefix = "%M"; # Magenta
   } elsif($input_length > $message_limit - 40) {
      $prefix = "%Y"; # Yellow
   } else {
      $prefix = "%G"; # Green
   }

   $item->default_handler($get_size_only, "{sb $prefix$chars_remaining%n}", undef, 1);
}

sub peep_statusbar_refresh {
   my $window = Irssi::active_win();
   
   # We identify peep windows by the server version string.
   my $in_peep_window = ($window->{active_server}->{version} =~ /^peep-/);

   # Get the current line of input.
   my $input = Irssi::parse_special("\$L");

   $input_length = length($input);
   
   if($in_peep_window == 1 && $statusbar_registered == 0 && $input_length > 0)
   {
      Irssi::statusbar_item_register('peep', undef, 'peep_statusbar');
      Irssi::statusbars_recreate_items();
      $statusbar_registered = 1;
   }
   elsif(($in_peep_window != 1 || $input_length == 0) && $statusbar_registered == 1)
   {
      Irssi::statusbar_item_unregister('peep');
      Irssi::statusbar_items_redraw('peep');
      $statusbar_registered = 0;
   }
   else
   {
      Irssi::statusbar_items_redraw('peep');
   }
}

Irssi::signal_add_last 'gui key pressed' => \&peep_statusbar_refresh;
Irssi::signal_add_last 'window changed' => \&peep_statusbar_refresh;


